var utils = require('../../../utils/util.js')
var c = require('../../../utils/config.js')
Page({
    data: {
        imgurl: [
            '/static/images/Carousel.png',
            '/static/images/Carousel.png',
            '/static/images/Carousel.png',
            '/static/images/Carousel.png'
        ],
        num: 1,
        scrollTop: 0,
        evaluationSelect: 0,
        Collection: false,
        hide: true,
        hide1: true,
        scroll_distance: '-660rpx',
        goodsId: 0,
        goodsPriceId: 0,
        img_url: c.img_url,
        checkList: [],
        goodsInfo: [],
        share_point: 0,
        share_start_content: "",
        share_end_content: "",
        integral:50,
        point_price:0
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var goodsPriceId = options.id;
        if (options.invitecode){
          wx.setStorageSync("invitecode", options.invitecode);
        }
        this.setData({
            goodsPriceId: goodsPriceId
        });
        this.getGoodDetail();
        this.getShareInfo();
    },
    getGoodDetail: function () {
        var goodsPriceId = this.data.goodsPriceId;
        var token = wx.getStorageSync("userinfo").wap_token;
        var that = this;
        var data = {
            url: "/wsgoods/goods/detail",
            page: 1,
            limit: 20,
            token: token,
            goods_price_id: goodsPriceId,
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                var data = res.data;
                var checkList = [];
                for (var i in data.spec) {
                    var arr = [];
                    for (var j in data.spec[i].lists) {
                        if (j == 0) {
                            arr[j] = { checked: 1 };
                        } else {
                            arr[j] = { checked: 0 };
                        }
                    }
                    checkList[i] = arr;
                };
                //js 正则详情图片
                data['content_pic'] = [];
                data.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
                    data['content_pic'].push(c.img_url + capture);
                });
                if (data.iscollect == 1){
                    that.setData({
                        Collection:true
                    });
                }
                data['point_price'] = (data['price']-data['point']).toFixed(2);
                that.setData({
                    goodsInfo: data,
                    goodsId: data.id,
                    checkList: checkList
                });

            } else {

            }
        });
    },
    //数量减
    bindMinus: function () {
        var num = this.data.num;
        if (num == 1) {
            wx.showToast({
                title: '数量不能小于1',
                icon: 'none',
                duration: 2000
            })
        } else {
            this.setData({
                num: num - 1
            })
        }
    },
    //数量加
    bindPlus: function () {
        var num = parseInt(this.data.num);
        if (num >= this.data.goodsInfo.p_stock) {
            utils.errMsg("不能大于库存!");
            return false;
        }
        this.setData({
            num: num + 1
        })
    },
    changeSpec: function (e) {//选择规格
        var index = e.currentTarget.dataset.index;
        var i = e.currentTarget.dataset.i;
        var checkList = this.data.checkList;
        for (var k in checkList[index]) {
            checkList[index][k].checked = 0;
        }
        checkList[index][i].checked = 1;
        this.setData({
            checkList: checkList
        })
        this.getGoodsPriceId();

    },
    getGoodsPriceId: function () {//获取规格ID
        var checkList = this.data.checkList;
        var goodsSpec = this.data.goodsInfo.spec;
        var specName = "";
        for (var a in goodsSpec) {
            for (var b in goodsSpec[a].lists) {
                if (checkList[a][b].checked == 1) {
                    specName = specName + goodsSpec[a].lists[b].title + "_";
                }
            }
        }
        specName = specName.substr(0, specName.length - 1);
        var goodsId = this.data.goodsId;
        var goodsInfo = this.data.goodsInfo;
        var that = this;
        var data = {
            url: "/wsgoods/goods/findgoods",
            goods_id: goodsId,
            title: specName
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                var data = res.data;
                goodsInfo.price = data.price;
                goodsInfo.p_stock = data.stock;
                that.setData({
                    goodsInfo: goodsInfo,
                    goodsPriceId: data.id
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    addCart: function () {//添加购物车
        var goodsPriceId = this.data.goodsPriceId;
        if (!utils.checkLogin()){
            return false;
        }
        var nums = this.data.num;
        var token = wx.getStorageSync("userinfo").wap_token;

        if (goodsPriceId == 0) {
            goodsPriceId = this.data.goodsInfo.goods_price_id;
        }
        var that = this;
        var data = {
            url: "/wsgoods/Ordercart/edit",
            goods_price_id: goodsPriceId,
            nums: nums,
            token: token
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                wx.showToast({
                    title: "添加成功",
                    icon: 'success',
                    duration: 2000
                })
                that.close();
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                })
            }
        });
    },
    confirmOrder: function () {//立即购买
        if (!utils.checkLogin()) {
            return false;
        }
        var arr = [];
        var goodsInfo = this.data.goodsInfo;
        var goodsPriceId = this.data.goodsPriceId;
        var nums = this.data.num;
        var token = wx.getStorageSync("userinfo").wap_token;
        if (goodsPriceId == 0) {
            goodsPriceId = this.data.goodsInfo.goods_price_id;
        }
        arr[0] = { "title": goodsInfo.title, "nums": nums, "price": goodsInfo.price, id: goodsPriceId, pic: goodsInfo.pic, "point": goodsInfo.point };
        arr = JSON.stringify(arr);
        var goodsExt = { goods_type: goodsInfo.goods_type, totalNums: nums, totalMoney: goodsInfo.price * nums, totalPoint: goodsInfo.point * nums };
        goodsExt = JSON.stringify(goodsExt);
        if (arr.length == 0) {
            wx.showToast({
                title: '必须选择一件商品!',
                icon: "none"
            })
            return false;
        }
        this.close();
        wx.navigateTo({
            url: '/pages/shop/confirmorder/index?orderGoods=' + arr + "&goodsExt=" + goodsExt,
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        var invitecode = wx.getStorageSync("userinfo").invitecode;
        if (!invitecode){
            invitecode = 0;
        }
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }
        var id = this.data.goodsPriceId;
        var name = this.data.goodsInfo.title;
        var pic = this.data.img_url+this.data.goodsInfo.pic;
        console.log('/pages/shop/goodsdetail/index?id=' + id + "&invitecode=" + wx.getStorageSync("userinfo").invitecode)
        return {
            title: this.data.share_start_content + name +  "￥" + this.data.goodsInfo.price + this.data.share_end_content,
            path: '/pages/shop/goodsdetail/index?id=' + id + "&invitecode=" + wx.getStorageSync("userinfo").invitecode,
            imageUrl: pic,
            success: function (res) {
                var data = {
                    url: "/wsgoods/usershare/add",
                    token: token,
                    type: 0,
                    id: this.data.goodsId
                };
                utils.request(data).then(function (res) {
                    if (res.code == 0) {
                        utils.sucMsg("分享成功");
                    } else {

                    }
                });
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },
    getShareInfo: function () {
        var that = this;
        var data = {
            url: "/zfcom/com/deploy",
            uuid: "share_point,share_start_content,share_end_content",
        };
        utils.request(data).then(function (res) {
            if (res.code == 0) {
                that.setData({
                    share_point: res.data.share_point,
                    share_start_content: res.data.share_start_content,
                    share_end_content: res.data.share_end_content,
                });
            }
        });
    },
    chooseCatalog: function (e) {
        let key = e.currentTarget.dataset.select;
        if (key) {
            this.setData({
                scrollTop: 435
            })
        }
        this.setData({
            catalogSelect: key
        })
    },
    Collection: function () {
        utils.checkLogin();
        var token = wx.getStorageSync("userinfo").wap_token;
        if (this.data.Collection){
            var data = {
                url: "/wsgoods/usercollect/del",
                token: token,
                type: 0,
                id: this.data.goodsId
            };
            utils.request(data).then(function (res) {
                if (res.code == 0) {
                    wx.showToast({
                        title: '取消收藏成功',
                        icon: 'success',
                        duration: 2000
                    })
                } else {

                }
            });
        }else{
            var data = {
                url: "/wsgoods/usercollect/add",
                token: token,
                type:0,
                id: this.data.goodsId
            };
            utils.request(data).then(function (res) {
                if (res.code == 0) {
                    wx.showToast({
                        title: '收藏成功',
                        icon: 'success',
                        duration: 2000
                    })
                }
            });
        }

        this.setData({
            Collection: !this.data.Collection
        })
    },
    close: function () {
        this.setData({
            hide: true,
            hide1: true,
            scroll_distance: '-660rpx'
        })
    },
    add_cart: function () {
        this.setData({
            hide: false,
        });
        this.scroll_distance()
    },
    buy_btn: function () {
        this.setData({
            hide1: false,
        });
        this.scroll_distance()
    },
    scroll_distance: function () {
        this.setData({
            scroll_distance: 0
        })
    },
    openIndex: function () {
        wx.switchTab({
            url: '/pages/shop/shop/index'
        })
    },
    //输入框
    editNums:function(e){
        if (e.detail.value >= this.data.goodsInfo.p_stock){
            //utils.errMsg("不能大于库存!");
            this.setData({
                num: this.data.goodsInfo.p_stock
            })
            return;
        }
        this.setData({
            num: e.detail.value
        })
    },
    openCart:function(){
        wx.switchTab({
            url: '/pages/shop/ordercart/index'
        })
    }
})
